from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    '''
    和用户关联的个人资料
    '''
    nickname = models.CharField(max_length=20, blank=True, verbose_name='昵称')
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    def __str__(self):
        return '<Profile>:{} for {}'.format(self.nickname, self.user.username)


# 采用动态绑定，方便通过user获取nickname
def get_nickname(self):
    if Profile.objects.filter(user=self).exists():
        return self.profile.nickname
    else:
        return ''

def get_nickname_or_username(self):
    if Profile.objects.filter(user=self).exists():
        return self.profile.nickname
    else:
        return self.username

User.get_nickname = get_nickname
User.get_nickname_or_username = get_nickname_or_username